﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TagThisOrgProject.Models;

namespace TagThisOrgProject.Repository
{
    public class UserUrlSettingsRepository
    {
        private TagContext Context { get; set; }
        private UrlRepository UrlRepo { get; set; }
        private UserRepository UserRepo { get; set; }
        public UserUrlSettingsRepository(TagContext context)
        {
            this.Context = context;
        }

        public UserUrlSettings AddSettings(Int64 UrlId, int UserId, UserUrlSettings settings, bool isSafeUser = true, bool isForSave = true)
        {

            if (!isSafeUser)
            {
                if (UserRepo == null)
                    UserRepo = new UserRepository(Context);
                var user = UserRepo.GetUser(UserId);
                if (user == null)
                    throw new Exception("Пользователь не найдден. Код 0009");
            }
            settings.UrlId = UrlId;
            settings.UserId = UserId;
            settings = Context.UserUrlSettings.Add(settings);
            if (isForSave)
            {
                try
                {
                    Context.SaveChanges();
                }
                catch
                {
                    throw new Exception("Не удалось сохранить название. Код 0010");
                }
            }
            return settings;
        }

        public UserUrlSettings AddSettings(Url url, UserProfile user, UserUrlSettings settings, bool isSafeUser = true,  bool isForSave = true)
        {
            return this.AddSettings(url.UrlId, user.UserId , settings, isSafeUser, isForSave);
        }

        public UserUrlSettings ChangeSettings(Int64 UrlSettingsId ,UserUrlSettings settings)
        {
            var sttngs =  GetUserUrlSettings(UrlSettingsId);
            if (sttngs == null)
                throw new Exception("Не удлось изменить настройки, т.к. их не существует. Код 0011");
            sttngs.Title = settings.Title;
            try
            {
                this.Context.SaveChanges();
            }
            catch
            {
                throw new Exception("Не удлось изменить настройки. Код 0012");
            }
            return sttngs;
        }

        public UserUrlSettings GetUserUrlSettings (Int64 urlId, int UserId)
        {
            return (from s in Context.UserUrlSettings
                    where s.UserId == UserId && s.UrlId == urlId
                    select s).FirstOrDefault();
        }

        public UserUrlSettings GetUserUrlSettings(Int64 UserUrlSettingsId)
        {
            return (from s in Context.UserUrlSettings
                    where s.UserUrlSettingsId == UserUrlSettingsId
                    select s).FirstOrDefault();
        }
    }
}